# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=lapack
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.11.0
pkgrel=3
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
pkgdesc="Linear Algebra PACKage (mingw-w64)"
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
license=('spdx:BSD-3-Clause')
url="https://www.netlib.org/lapack"
source=(${_realname}-${pkgver}.tar.gz::https://github.com/Reference-LAPACK/lapack/archive/v${pkgver}.tar.gz)
sha256sums=('4b9ba79bfd4921ca820e83979db76ab3363155709444a787979e81c22285ffa9')

build() {
  declare -a _extra_config
  if check_option "debug" "y"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  fi

  mkdir -p "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake.exe \
      -G"Ninja" \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      ${_extra_config[@]} \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_NEED_RESPONSE=ON \
      -DBUILD_TESTING=OFF \
      -DLAPACKE_WITH_TMG=ON \
      -DCBLAS=ON \
      -DBUILD_DEPRECATED=ON \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build .

  mkdir -p "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake.exe \
      -G"Ninja" \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      ${_extra_config[@]} \
      -DBUILD_SHARED_LIBS=OFF \
      -DBUILD_TESTING=OFF \
      -DLAPACKE_WITH_TMG=ON \
      -DCBLAS=ON \
      -DBUILD_DEPRECATED=ON \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build .
}

check() {
  # Many of the tests for CBLAS are failing

  cd "${srcdir}/build-${MSYSTEM}-shared"
  ${MINGW_PREFIX}/bin/cmake.exe -DBUILD_TESTING=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake.exe --build .
  ${MINGW_PREFIX}/bin/ctest . || true

  cd "${srcdir}/build-${MSYSTEM}-static"
  ${MINGW_PREFIX}/bin/cmake.exe -DBUILD_TESTING=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake.exe --build .
  ${MINGW_PREFIX}/bin/ctest . || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
